package com.group3.merchant.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public UploadServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		request.setCharacterEncoding("utf-8");
		if (isMultipart) {
			File tempFile = new File("d://tempFile");
			if (!tempFile.exists()) {
				tempFile.mkdir();
			}
			// upload
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(2 * 1024);

			factory.setRepository(tempFile);

			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(10 * 1024 * 1024);
			String fileName="";
			// get forms through upload
			try {
				List<FileItem> list = upload.parseRequest(request);
				Iterator<FileItem> i = list.iterator();
				while (i.hasNext()) {
					FileItem item = i.next();
					if (item.isFormField()) {
						System.out.println(item.getFieldName() + "..."
								+ item.getString("utf-8"));
					} else {
						fileName = item.getName()+ UUID.randomUUID();
						System.out.println("file size:" + item.getSize());
						System.out.println("file name:" + item.getName());

						System.out
								.println("file type:" + item.getContentType());

						File f = new File("d:/upload/" 
								+ fileName);
						item.write(f);

					}
					
				}
				writer.write(fileName);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
		}
	}

}
